/*
 * @# ReplicationToDb.java 2011-11-10 下午04:38:18
 * 
 * Copyright (C) 2010 - 2011 广州羿安信息科技有限公司
 * Guangzhou ianswer information technology co. ltd.
 * 
 * All rights reserved!
 */
package com.ianswer.experiments.redis.sync;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang.math.RandomUtils;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

import com.ianswer.common.orm.PublicDao;
import com.ianswer.common.util.Asserts;
import com.ianswer.experiments.redis.DataUtils;
import com.ianswer.experiments.redis.RedisDemo;

/**
 * @author alvin hwang
 */
public class ReplicationToDb {

	private static final String HOST = "192.168.1.105";
	private static final int PORT = 6379;

	private static Logger log = LoggerFactory.getLogger(ReplicationToDb.class);

	private Jedis jedis;
	PublicDao publicDao;

	public ReplicationToDb() {
		jedis = new Jedis(HOST, PORT);
		publicDao = DataUtils.getBean("publicDao", PublicDao.class);
	}

	/**
	 * 方案一: 先写mysql, 再写redis.
	 * 
	 * <ol>
	 * 优点:
	 * <li>部署简单
	 * <li>可以确保数据库里的数据正确
	 * </ol>
	 * 
	 * <ol>
	 * 缺点:
	 * <li>同时操纵, 逻辑复杂
	 * <li>执行效率不高
	 * </ol>
	 */
	public Long simpleInsert() {
		RedisDemo data = new RedisDemo();
		data.setName("新插入的值");
		data.setDescription("" + System.currentTimeMillis());
		data.setAge(RandomUtils.nextInt());

		Long id = (Long) publicDao.insert("redisDemo.insert", data);
		data.setId(id);
		put(data);

		return id;
	}

	private Map<String, String> put(RedisDemo data) {
		Map<String, String> cache = new HashMap<String, String>();
		cache.put("name", data.getName());
		cache.put("description", data.getDescription());
		cache.put("age", String.valueOf(data.getAge()));

		jedis.hmset("redis-demo-" + data.getId(), cache);

		return cache;
	}

	private void assertRedisExists(Long id) {
		Asserts.assertNotEmpty(jedis.hgetAll("redis-demo-" + id));
	}

	public static void main(String[] args) {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();

		ReplicationToDb replicationToDb = new ReplicationToDb();
		Long id = replicationToDb.simpleInsert();

		stopWatch.stop();
		log.debug("ReplicationToDb simpleInsert 总运行时间为: {}", stopWatch.toString());
		
		replicationToDb.assertRedisExists(id);
	}
}
